using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using HuiLian.Common.Input;
using HuiLian.Common.Output;
using HuiLian.Model.Platform;
using HuiLian.Service.Platform.Repairledget;
using HuiLian.Service.Platform.Repairledget.Input;
using HuiLian.Common.Auth;
using HuiLian.Common.Configs;
using HuiLian.Common.Helpers;
using Microsoft.Extensions.Options;
using HuiLian.Web.Attributes;
using Microsoft.AspNetCore.Http;
using System.Data;
using System;
using System.Diagnostics;
using Org.BouncyCastle.Crypto;
using System.IO;
using HuiLian.Common;
using System.Web;

namespace HuiLian.Web.Controllers.Platform
{
    /// <summary>
    /// 修漏作业记录管理
    /// </summary>
    public class RepairledgetController : AreaController
    {
        private readonly IUser _user;
        private readonly UploadConfig _uploadConfig;
        private readonly UploadHelper _uploadHelper;
        private readonly ExcelHelper _excelHelper;
        private readonly IRepairledgetService _repairledgetServices;
        private readonly ParamConfig _paramConfig;

        public RepairledgetController(
            IUser user,
            IOptionsMonitor<UploadConfig> uploadConfig,
            UploadHelper uploadHelper,
            ExcelHelper excelHelper, 
            IRepairledgetService repairledgetServices,
            IOptionsMonitor<ParamConfig> paramConfig)
        {
            _user = user;
            _uploadConfig = uploadConfig.CurrentValue;
            _uploadHelper = uploadHelper;
            _excelHelper = excelHelper;
            _repairledgetServices = repairledgetServices;
            _paramConfig = paramConfig.CurrentValue;
        }

        /// <summary>
        /// 查询单条修漏作业记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IResponseOutput> Get(long id)
        {
            return await _repairledgetServices.GetAsync(id);
        }

        /// <summary>
        /// 查询分页修漏作业记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> GetPage(PageInput<RepairledgetEntity> model)
        {
            return await _repairledgetServices.PageAsync(model);
        }

        /// <summary>
        /// 新增修漏作业记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> Add(RepairledgetAddInput input)
        {
            return await _repairledgetServices.AddAsync(input);
        }

        /// <summary>
        /// 修改修漏作业记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IResponseOutput> Update(RepairledgetUpdateInput input)
        {
            return await _repairledgetServices.UpdateAsync(input);
        }

        /// <summary>
        /// 删除修漏作业记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IResponseOutput> SoftDelete(long id)
        {
            return await _repairledgetServices.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量删除修漏作业记录
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IResponseOutput> BatchSoftDelete(long[] ids)
        {
            return await _repairledgetServices.BatchSoftDeleteAsync(ids);
        }

        /// <summary>
        /// 数据导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Login]
        public async Task<IResponseOutput> ExcelImport(IFormFile file)
        {
            try
            {
                var config = _uploadConfig.Document;
                var res = await _uploadHelper.UploadAsync(file, config, new { _user.Id });
                if (res.Success)
                {
                    _excelHelper.FilePath = @$"{config.UploadPath}\{res.Data.FileRelativePath}";
                    _excelHelper.ToDataTable_repairledget();
                    DataTable dt = _excelHelper._dataTable;
                    var list = ExtendHelper.GetList<RepairledgetEntity>(dt);

                    await _repairledgetServices.AddListAsync(list);
                    //await _repairledgetServices.UpdateCount();
                    //await _repairledgetServices.UpdatePuChaYear();
                    return ResponseOutput.Result(true);
                }

                return ResponseOutput.NotOk("上传失败！");
            }
            catch (Exception ex) { return ResponseOutput.NotOk(ex.Message); }
        }

        /// <summary>
        /// 数据匹配
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IResponseOutput> DataPiPei()
        {
            return await _repairledgetServices.DataPiPei();
        }

        /// <summary>
        /// 运行模型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IResponseOutput> RunModel()
        {
            try
            {
                string exePath = Path.Combine(AppContext.BaseDirectory, _paramConfig.modelExePath).ToPath();
                Process ProgStock = ProcessHandler.CreateProcessAsUser(exePath, "args");
                //ProgStock.WaitForExit();//使当前线程处于等待状态，直到关联的进程终止

                #region 这是另一种调用exe的方法
                //Process ProgStock = new Process();
                //ProgStock.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;  //应用程序所在目录
                //ProgStock.StartInfo.UseShellExecute = false;
                //ProgStock.StartInfo.RedirectStandardOutput = true;
                //ProgStock.StartInfo.CreateNoWindow = true;

                //ProgStock.StartInfo.FileName = Path.Combine(AppContext.BaseDirectory, _paramConfig.modelExePath).ToPath();  //执行程序完整路径
                ////ProgStock.StartInfo.Arguments = "1";   //参数
                //ProgStock.Start();

                //ProgStock.WaitForExit();//使当前线程处于等待状态，直到关联的进程终止
                #endregion
            }
            catch (Exception ex)
            {
                return ResponseOutput.NotOk(ex.Message + "   " + ex.StackTrace);
            }
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 更新管线的维修次数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> UpdateCount()
        {
            return await _repairledgetServices.UpdateCount();
        }

        /// <summary>
        /// 更新普查年份
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> UpdatePuChaYear()
        {
            return await _repairledgetServices.UpdatePuChaYear();
        }

        /// <summary>
        /// 运行管线预期时间模型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IResponseOutput> RunPipeSurvivalTimeModel()
        {
            try
            {
                string exePath = Path.Combine(AppContext.BaseDirectory, _paramConfig.pipeSurvivalTimeExePath).ToPath();                
                Process ProgStock = ProcessHandler.CreateProcessAsUser(exePath, "");
                //ProgStock.WaitForExit();//使当前线程处于等待状态，直到关联的进程终止

                #region 这是另一种调用exe的方法
                //Process ProgStock = new Process();
                //ProgStock.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;  //应用程序所在目录
                //ProgStock.StartInfo.UseShellExecute = false;
                //ProgStock.StartInfo.RedirectStandardOutput = true;
                //ProgStock.StartInfo.CreateNoWindow = true;

                //ProgStock.StartInfo.FileName = Path.Combine(AppContext.BaseDirectory, _paramConfig.modelExePath).ToPath();  //执行程序完整路径
                ////ProgStock.StartInfo.Arguments = "1";   //参数
                //ProgStock.Start();

                //ProgStock.WaitForExit();//使当前线程处于等待状态，直到关联的进程终止
                #endregion
            }
            catch (Exception ex)
            {
                return ResponseOutput.NotOk(ex.Message + "   " + ex.StackTrace);
            }
            return ResponseOutput.Ok();
        }
    }
}
